<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Message as MessageModel;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\Response;

class Message extends Base
{
    public function index(): Response
    {
        $list = MessageModel::getPageList(['uid' => $this->user->id],
            'id,content,images,status,rcomment,reply_time,create_time',
            $this->getPage(), $this->getLimit(), false);
        foreach ($list['data'] as &$item) {
            $item->images = $item->images ? explode(',', $item->images) : '';
        }

        return Result::fastReturn($list);
    }

    public function save(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Message');
        } catch (ValidateException $e) {
            return Result::fail(['code' => -1, 'msg' => $e->getError()]);
        }
        $res = MessageModel::add($param, $this->user);
        if ($res['code'] === -1) {
            return Result::fail($res['msg']);
        }

        return Result::success($res['msg']);
    }
}